package replay;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;

import uk.ac.nott.cs.g53dia.Action;
import valueobj.SimulationSettings;

public class Recorder {
	private static final String SEP = "-";
	private static final String EXT = ".txt";
	private static final String PREFIX = "./replays/";
	private boolean initialized = false;
	private BufferedWriter bw;

	private String getReplayName() {
		Calendar c = new GregorianCalendar();
		return PREFIX + c.get(Calendar.YEAR) + SEP + c.get(Calendar.MONDAY)
				+ SEP + c.get(Calendar.DATE) + SEP
				+ c.get(Calendar.HOUR_OF_DAY) + SEP + c.get(Calendar.MINUTE)
				+ SEP + c.get(Calendar.SECOND) + EXT;
	}

	public void init(SimulationSettings settings) {
		File dir = new File(PREFIX);
		if (!dir.exists()) {
			dir.mkdir();
		}
		String name = getReplayName();
		try {
			bw = new BufferedWriter(new FileWriter(name, true));
		} catch (IOException e) {
			e.printStackTrace();
		}
		initialized = true;
		writeSettings(settings, name);
	}

	public void writeAction(Action action) {
		append(action.getCode());
	}

	private void writeSettings(SimulationSettings settings, String name) {
		String comment = "# " + name
				+ " (number of bees, duration, random seed)";
		String sets = settings.getBeesNum() + ";" + settings.getDuration()
				+ ";" + settings.getRandomSeed();
		append(comment + "\n" + sets);
	}

	public void append(String record) {
		if (!initialized)
			throw new IllegalStateException("Initialize recorder first.");
		try {
		  System.out.println(record);
			bw.append(record);
			bw.newLine();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void close() {
		if (bw != null) {
			try {
				bw.flush();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				bw = null;
			}
		}
	}

}
